"""

"""

import os
from kivymd.uix.screen import MDScreen
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.scrollview import MDScrollView
from kivymd.uix.card import MDCard
from kivymd.uix.label import MDLabel
from kivymd.uix.button import MDRaisedButton, MDFlatButton
from kivymd.uix.toolbar import MDTopAppBar
from kivymd.uix.tab import MDTabs, MDTabsBase
from kivymd.app import MDApp
from kivymd.toast import toast

try:
    from plyer import sharing
    from plyer import storagepath
    PLYER_AVAILABLE = True
except ImportError:
    PLYER_AVAILABLE = False

from ...core.output_formatter import OutputFormatter

class Tab(MDBoxLayout, MDTabsBase):
    """"""
    pass

class ResultScreen(MDScreen):
    """"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._build_ui()

    def on_enter(self):
        """"""
        app = MDApp.get_running_app()
        result_data = getattr(app, 'result_data', None)
        if result_data:
            self._update_content(result_data)
        else:
            toast("")
            self._update_content(self._get_sample_data()) # 

    def _build_ui(self):
        """"""
        main_layout = MDBoxLayout(orientation='vertical', spacing="10dp")
        toolbar = MDTopAppBar(
            title="",
            left_action_items=[
                ["arrow-left", lambda x: self._go_back()]
            ],
            right_action_items=[
                ["share-variant", lambda x: self._share_result()],
                ["download", lambda x: self._save_result(file_format='md')]
            ]
        )
        main_layout.add_widget(toolbar)

        self.tabs = MDTabs()
        main_layout.add_widget(self.tabs)

        # Create tabs and content widgets
        self.summary_content_area = self._create_summary_content()
        self.keywords_content_area = self._create_keywords_content()
        self.chapters_content_area = self._create_chapters_content()
        self.transcript_content_area = self._create_transcript_content()

        self.tabs.add_widget(Tab(self.summary_content_area, title=" "))
        self.tabs.add_widget(Tab(self.keywords_content_area, title=" "))
        self.tabs.add_widget(Tab(self.chapters_content_area, title=" "))
        self.tabs.add_widget(Tab(self.transcript_content_area, title=" "))

        button_layout = MDBoxLayout(orientation='horizontal', spacing="15dp", padding="20dp", size_hint_y=None, height="70dp")
        new_btn = MDFlatButton(text=" ", size_hint_x=0.5)
        new_btn.bind(on_press=self._process_new_video)
        button_layout.add_widget(new_btn)
        save_btn = MDRaisedButton(text="  (MD)", size_hint_x=0.5, md_bg_color=self.theme_cls.primary_color)
        save_btn.bind(on_press=lambda x: self._save_result(file_format='md'))
        button_layout.add_widget(save_btn)
        main_layout.add_widget(button_layout)

        self.add_widget(main_layout)

    def _update_content(self, data):
        """UI"""
        # Summary Tab
        summary_data = data.get('summary', {})
        self.summary_text.text = summary_data.get('summary', '')
        
        transcript_len = len(data.get('transcript', {}).get('text', ''))
        summary_len = len(summary_data.get('summary', ''))
        ratio = (summary_len / transcript_len * 100) if transcript_len > 0 else 0
        self.stats_text.text = f": {transcript_len} \n: {summary_len} \n: {ratio:.1f}%"

        # Keywords Tab
        keywords = summary_data.get('keywords', [])
        self.keywords_text.text = '\n'.join([f"• {kw}" for kw in keywords]) if keywords else ""

        # Chapters Tab
        chapters = summary_data.get('chapters', [])
        self.chapters_list.clear_widgets()
        if chapters:
            for i, chapter in enumerate(chapters, 1):
                chapter_card = MDCard(orientation='vertical', padding="15dp", spacing="10dp", size_hint_y=None, adaptive_height=True, elevation=2)
                chapter_title = MDLabel(text=f"{i}: {chapter.get('title', '')}", theme_text_color="Primary", font_style="Subtitle1", adaptive_height=True)
                chapter_card.add_widget(chapter_title)
                chapter_content = MDLabel(text=chapter.get('content', ''), theme_text_color="Secondary", font_style="Body2")
                chapter_card.add_widget(chapter_content)
                self.chapters_list.add_widget(chapter_card)
        else:
            self.chapters_list.add_widget(MDLabel(text="", halign="center"))

        # Transcript Tab
        self.transcript_text.text = data.get('transcript', {}).get('text', '')

    def _create_summary_content(self):
        scroll = MDScrollView()
        content = MDBoxLayout(orientation='vertical', spacing="15dp", padding="20dp", adaptive_height=True)
        summary_card = MDCard(orientation='vertical', padding="20dp", spacing="10dp", size_hint_y=None, adaptive_height=True, elevation=2)
        summary_card.add_widget(MDLabel(text=" ", theme_text_color="Primary", font_style="H6", size_hint_y=None, height="40dp"))
        self.summary_text = MDLabel(text="", theme_text_color="Secondary", font_style="Body1")
        summary_card.add_widget(self.summary_text)
        content.add_widget(summary_card)
        stats_card = MDCard(orientation='vertical', padding="20dp", spacing="10dp", size_hint_y=None, height="150dp", elevation=2)
        stats_card.add_widget(MDLabel(text=" ", theme_text_color="Primary", font_style="H6", size_hint_y=None, height="40dp"))
        self.stats_text = MDLabel(text="", theme_text_color="Secondary", font_style="Body2")
        stats_card.add_widget(self.stats_text)
        content.add_widget(stats_card)
        scroll.add_widget(content)
        return scroll

    def _create_keywords_content(self):
        scroll = MDScrollView()
        content = MDBoxLayout(orientation='vertical', spacing="15dp", padding="20dp", adaptive_height=True)
        keywords_card = MDCard(orientation='vertical', padding="20dp", spacing="10dp", adaptive_height=True, elevation=2)
        keywords_card.add_widget(MDLabel(text=" ", theme_text_color="Primary", font_style="H6", size_hint_y=None, height="40dp"))
        self.keywords_text = MDLabel(text="", theme_text_color="Secondary", font_style="Body1")
        keywords_card.add_widget(self.keywords_text)
        content.add_widget(keywords_card)
        scroll.add_widget(content)
        return scroll

    def _create_chapters_content(self):
        scroll = MDScrollView()
        self.chapters_list = MDBoxLayout(orientation='vertical', spacing="15dp", padding="20dp", adaptive_height=True)
        scroll.add_widget(self.chapters_list)
        return scroll

    def _create_transcript_content(self):
        scroll = MDScrollView()
        content = MDBoxLayout(orientation='vertical', spacing="15dp", padding="20dp", adaptive_height=True)
        transcript_card = MDCard(orientation='vertical', padding="20dp", spacing="10dp", adaptive_height=True, elevation=2)
        transcript_card.add_widget(MDLabel(text=" ", theme_text_color="Primary", font_style="H6", size_hint_y=None, height="40dp"))
        self.transcript_text = MDLabel(text="", theme_text_color="Secondary", font_style="Body2")
        transcript_card.add_widget(self.transcript_text)
        content.add_widget(transcript_card)
        scroll.add_widget(content)
        return scroll

    def _go_back(self):
        MDApp.get_running_app().navigate_to('main')

    def _share_result(self):
        app = MDApp.get_running_app()
        result_data = getattr(app, 'result_data', None)
        if not result_data or not PLYER_AVAILABLE:
            toast("")
            return
        summary_text = result_data.get('summary', {}).get('summary', '')
        title = f": {result_data.get('video_info', {}).get('original_name', '')}"
        try:
            sharing.share(title=title, text=summary_text)
        except Exception as e:
            toast(f": {e}")

    def _save_result(self, file_format='md'):
        app = MDApp.get_running_app()
        result_data = getattr(app, 'result_data', None)
        if not result_data:
            toast("")
            return
        try:
            if PLYER_AVAILABLE:
                downloads_path = storagepath.get_downloads_dir()
            else:
                downloads_path = os.path.join(os.path.expanduser("~"), "Downloads")
            
            from pathlib import Path
            Path(downloads_path).mkdir(exist_ok=True)
            
            video_name = Path(result_data.get('video_info', {}).get('file_path', 'result')).stem
            output_path = os.path.join(downloads_path, f"{video_name}.{file_format}")

            formatter = OutputFormatter()
            formatter.save_result(result_data, output_path, file_format)
            toast(f": {output_path}")
        except Exception as e:
            toast(f": {e}")

    def _process_new_video(self, instance):
        MDApp.get_running_app().navigate_to('upload')

    def _get_sample_data(self):
        return {
            'transcript': {'text': ''},
            'summary': {'summary': '', 'keywords': [''], 'chapters': []},
            'video_info': {'original_name': '.mp4'},
            'processing_time': 'N/A'
        }
